import json
import time

import pymysql
from django.http import HttpResponse
from django.shortcuts import render
from functools import reduce
# Create your views here.
from untitled7.settings import ELASTICSEARCH
from elasticsearch import Elasticsearch


def health(request):
    data = {'status': 'up'}
    return HttpResponse(json.dumps(data), content_type='application/json')


def syslog_sum(request):
    # es = Elasticsearch([ELASTICSEARCH])
    # find_sql = {
    #     "query": {
    #         "range": {
    #             "time": {
    #                 "gte": time.time() - 1
    #             }
    #         }
    #     }
    # }
    # data = es.search(index="syslog", doc_type="log1", body=find_sql)
    # data_dict = {}
    # for i in data["hits"]["hits"]:
    #     data_dict[i["_source"]["hostname"]] = i["_source"]["disk"]["disk_industry_data"]["data_use"]

    # data_sum = reduce(lambda i, j: i + j, data_dict.values())
    def my_sqls():
        cursor = pymysql.connect(user='beacon', password='Foxconn88!',
                                 host='172.16.16.134', port=3306, db='elasticsearch')
        # cursor = pymysql.connect(user='root', password='root',
        #                          host='127.0.0.1', port=3306, db='elasticsearch')
        sql_conn = cursor.cursor()
        return cursor, sql_conn

    cursor, sql_conn = my_sqls()
    sql_conn.execute("select sum(data_size) from elasticsearch")
    data_sum = sql_conn.fetchone()[0]
    k = {
        "status": 0,
        "payload": [{
            "label": "累计工业数据量",
            "value": "%.2f" % (data_sum / (1024 * 1024 * 1024)) + "GB"
        }],
        "errmsg": ""
    }
    sql_conn.close()
    cursor.close()
    return HttpResponse(json.dumps(k), content_type="application/json")
    # return HttpResponse("hello", content_type="application/json")

